<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="~{admin/layout/base :: html(
        title='回收站管理',
        content=~{::content},
        scripts=~{::scripts},
        currentPage='stations'
      )}">
<body>
    <th:block th:fragment="content">
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="search-box flex-grow-1 me-3">
                        <i class='bx bx-search'></i>
                        <input type="text" class="form-control" id="searchInput" placeholder="搜索回收站...">
                    </div>
                    <button class="btn btn-primary" id="addStationBtn">
                        <i class='bx bx-plus'></i> 新增回收站
                    </button>
                </div>
            </div>
        </div>

        <div class="table-card">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>名称</th>
                            <th>地址</th>
                            <th>联系电话</th>
                            <th>营业时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr th:each="station : ${stations}">
                            <td th:text="${station.id}">1</td>
                            <td th:text="${station.name}">示例回收站</td>
                            <td th:text="${station.address}">示例地址</td>
                            <td th:text="${station.contactPhone}">13800138000</td>
                            <td th:text="${station.businessHours}">09:00-18:00</td>
                            <td>
                                <span th:class="${station.status == 1 ? 'status-badge success' : 'status-badge danger'}"
                                      th:text="${station.status == 1 ? '营业中' : '已关闭'}">
                                    营业中
                                </span>
                            </td>
                            <td>
                                <div class="btn-group">
                                    <button class="btn btn-icon btn-outline-primary me-1 edit-station" 
                                            th:data-id="${station.id}">
                                        <i class='bx bx-edit-alt'></i>
                                    </button>
                                    <button class="btn btn-icon btn-outline-danger delete-station"
                                            th:data-id="${station.id}">
                                        <i class='bx bx-trash'></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <div class="d-flex justify-content-between align-items-center mt-4">
                <div class="text-muted">
                    共 <span th:text="${stations.size()}">0</span> 条记录
                </div>
                <nav>
                    <ul class="pagination">
                        <li class="page-item disabled">
                            <a class="page-link" href="#"><i class='bx bx-chevron-left'></i></a>
                        </li>
                        <li class="page-item active">
                            <a class="page-link" href="#">1</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#">2</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#">3</a>
                        </li>
                        <li class="page-item">
                            <a class="page-link" href="#"><i class='bx bx-chevron-right'></i></a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>

        <!-- 新增/编辑回收站模态框 -->
        <div class="modal fade" id="stationModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">新增回收站</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="stationForm">
                            <input type="hidden" id="stationId">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">回收站名称</label>
                                        <input type="text" class="form-control" id="name" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">地址</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="address" required>
                                            <button class="btn btn-outline-secondary" type="button" id="searchAddress">
                                                <i class='bx bx-search'></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">联系电话</label>
                                        <input type="tel" class="form-control" id="contactPhone" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">联系人</label>
                                        <input type="text" class="form-control" id="contactPerson">
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">营业时间</label>
                                        <input type="text" class="form-control" id="businessHours" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">可回收物品</label>
                                        <textarea class="form-control" id="acceptableItems" rows="3"></textarea>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">状态</label>
                                        <select class="form-select" id="status">
                                            <option value="1">营业中</option>
                                            <option value="0">已关闭</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">在地图上选择位置</label>
                                        <div id="map-container" style="height: 400px; border: 1px solid #ddd;"></div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">纬度</label>
                                                <input type="number" step="any" class="form-control" id="latitude" required readonly>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">经度</label>
                                                <input type="number" step="any" class="form-control" id="longitude" required readonly>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveStation()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </th:block>

    <th:block th:fragment="scripts">
        <!-- 添加百度地图API引用 -->
        <script th:inline="javascript">
            // 获取百度地图API密钥
            const BAIDU_MAP_KEY = [[${@environment.getProperty('baidu.map.apiKey')}]];
        </script>
        <script type="text/javascript" th:src="@{'https://api.map.baidu.com/api?v=3.0&ak=' + ${@environment.getProperty('baidu.map.apiKey')} + '&callback=initBaiduMap'}"></script>
        <script th:inline="javascript">
            let stationModal;
            let map;
            let marker;
            let searchTimeout;
            let mapInitialized = false;

            // 百度地图API加载完成的回调函数
            function initBaiduMap() {
                console.log('百度地图API加载完成');
                mapInitialized = true;
                if (stationModal) {
                    initMap();
                }
            }

            // 初始化地图
            function initMap() {
                if (!mapInitialized) {
                    console.log('等待百度地图API加载...');
                    return;
                }
                
                try {
                    console.log('初始化地图...');
                    // 初始化地图
                    map = new BMap.Map("map-container");
                    const point = new BMap.Point(116.404, 39.915); // 默认北京市中心
                    map.centerAndZoom(point, 12);
                    
                    // 添加地图控件
                    map.addControl(new BMap.NavigationControl());
                    map.addControl(new BMap.ScaleControl());
                    
                    // 启用滚轮缩放
                    map.enableScrollWheelZoom();

                    // 点击地图事件
                    map.addEventListener("click", function(e) {
                        setMarker(e.point);
                        updateCoordinates(e.point.lat, e.point.lng);
                        reverseGeocode(e.point);
                    });

                    console.log('地图初始化成功');
                } catch (error) {
                    console.error('地图初始化失败:', error);
                }
            }

            // 初始化页面
            document.addEventListener('DOMContentLoaded', function() {
                console.log('DOM加载完成');
                // 初始化模态框
                stationModal = new bootstrap.Modal(document.getElementById('stationModal'), {
                    keyboard: false,
                    backdrop: 'static'
                });

                // 如果百度地图API已加载完成，则初始化地图
                if (mapInitialized) {
                    initMap();
                }

                // 绑定新增按钮事件
                document.getElementById('addStationBtn').addEventListener('click', function() {
                    if (!mapInitialized) {
                        Swal.fire('提示', '地图正在加载中，请稍后再试', 'info');
                        return;
                    }
                    showAddStationModal();
                });

                // 绑定编辑按钮事件
                document.querySelectorAll('.edit-station').forEach(button => {
                    button.addEventListener('click', function() {
                        const id = this.getAttribute('data-id');
                        editStation(id);
                    });
                });

                // 绑定删除按钮事件
                document.querySelectorAll('.delete-station').forEach(button => {
                    button.addEventListener('click', function() {
                        const id = this.getAttribute('data-id');
                        deleteStation(id);
                    });
                });

                // 绑定地址搜索事件
                document.getElementById('searchAddress').addEventListener('click', function() {
                    const address = document.getElementById('address').value;
                    if (address) {
                        searchLocation(address);
                    }
                });

                // 绑定地址输入框回车事件
                document.getElementById('address').addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        const address = this.value;
                        if (address) {
                            searchLocation(address);
                        }
                    }
                });

                // 绑定搜索功能
                document.getElementById('searchInput').addEventListener('input', function(e) {
                    const searchTerm = e.target.value.toLowerCase();
                    const rows = document.querySelectorAll('tbody tr');
                    
                    rows.forEach(row => {
                        const text = row.textContent.toLowerCase();
                        row.style.display = text.includes(searchTerm) ? '' : 'none';
                    });
                });

                // 绑定模态框隐藏事件
                document.getElementById('stationModal').addEventListener('hidden.bs.modal', function () {
                    document.getElementById('stationForm').reset();
                    document.getElementById('stationId').value = '';
                    document.getElementById('modalTitle').textContent = '新增回收站';
                    if (marker) {
                        map.removeOverlay(marker);
                    }
                });
            });

            // 设置标记点
            function setMarker(point) {
                if (marker) {
                    map.removeOverlay(marker);
                }
                marker = new BMap.Marker(point);
                map.addOverlay(marker);
                map.panTo(point);
            }

            // 更新坐标输入框
            function updateCoordinates(lat, lng) {
                document.getElementById('latitude').value = lat;
                document.getElementById('longitude').value = lng;
            }

            // 地理编码（地址转坐标）
            function searchLocation(address) {
                const localSearch = new BMap.LocalSearch(map);
                localSearch.setSearchCompleteCallback(function(searchResult) {
                    if (searchResult && searchResult.getPoi(0)) {
                        const poi = searchResult.getPoi(0);
                        const point = poi.point;
                        setMarker(point);
                        updateCoordinates(point.lat, point.lng);
                        map.centerAndZoom(point, 16);
                    } else {
                        Swal.fire('提示', '未找到该地址，请尝试其他关键词', 'info');
                    }
                });
                localSearch.search(address);
            }

            // 反地理编码（坐标转地址）
            function reverseGeocode(point) {
                const geocoder = new BMap.Geocoder();
                geocoder.getLocation(point, function(result) {
                    if (result) {
                        document.getElementById('address').value = result.address;
                    }
                });
            }

            // 显示新增回收站模态框
            function showAddStationModal() {
                if (!map) {
                    console.log('初始化地图...');
                    initMap();
                }
                
                document.getElementById('stationForm').reset();
                document.getElementById('stationId').value = '';
                document.getElementById('modalTitle').textContent = '新增回收站';
                
                // 重置地图位置
                const point = new BMap.Point(116.404, 39.915);
                map.centerAndZoom(point, 12);
                if (marker) {
                    map.removeOverlay(marker);
                }
                
                stationModal.show();
            }

            // 编辑回收站
            function editStation(id) {
                fetch(`/admin/stations/${id}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('获取数据失败');
                        }
                        return response.json();
                    })
                    .then(station => {
                        document.getElementById('modalTitle').textContent = '编辑回收站';
                        document.getElementById('stationId').value = station.id;
                        document.getElementById('name').value = station.name || '';
                        document.getElementById('address').value = station.address || '';
                        document.getElementById('contactPhone').value = station.contactPhone || '';
                        document.getElementById('contactPerson').value = station.contactPerson || '';
                        document.getElementById('businessHours').value = station.businessHours || '';
                        document.getElementById('acceptableItems').value = station.acceptableItems || '';
                        document.getElementById('latitude').value = station.latitude || '';
                        document.getElementById('longitude').value = station.longitude || '';
                        document.getElementById('status').value = station.status || 1;
                        
                        stationModal.show();
                        
                        // 在地图上显示位置
                        if (station.latitude && station.longitude) {
                            const point = new BMap.Point(station.longitude, station.latitude);
                            setMarker(point);
                            map.centerAndZoom(point, 16);
                        }
                    })
                    .catch(error => {
                        console.error('获取回收站数据失败:', error);
                        Swal.fire('错误', '获取回收站数据失败', 'error');
                    });
            }

            // 删除回收站
            function deleteStation(id) {
                Swal.fire({
                    title: '确认删除',
                    text: '您确定要删除这个回收站吗？',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then((result) => {
                    if (result.isConfirmed) {
                        fetch(`/admin/stations/${id}`, {
                            method: 'DELETE'
                        })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('删除失败');
                            }
                            Swal.fire({
                                title: '成功',
                                text: '删除成功',
                                icon: 'success',
                                timer: 1500,
                                showConfirmButton: false
                            }).then(() => {
                                window.location.reload();
                            });
                        })
                        .catch(error => {
                            console.error('删除失败:', error);
                            Swal.fire('错误', '删除失败', 'error');
                        });
                    }
                });
            }

            // 保存回收站
            function saveStation() {
                const id = document.getElementById('stationId').value;
                const data = {
                    name: document.getElementById('name').value,
                    address: document.getElementById('address').value,
                    contactPhone: document.getElementById('contactPhone').value,
                    contactPerson: document.getElementById('contactPerson').value,
                    businessHours: document.getElementById('businessHours').value,
                    acceptableItems: document.getElementById('acceptableItems').value,
                    latitude: parseFloat(document.getElementById('latitude').value),
                    longitude: parseFloat(document.getElementById('longitude').value),
                    status: parseInt(document.getElementById('status').value)
                };

                const url = id ? `/admin/stations/${id}` : '/admin/stations';
                const method = id ? 'PUT' : 'POST';

                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('保存失败');
                    }
                    stationModal.hide();
                    Swal.fire({
                        title: '成功',
                        text: '保存成功',
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.reload();
                    });
                })
                .catch(error => {
                    console.error('保存失败:', error);
                    Swal.fire('错误', '保存失败', 'error');
                });
            }
        </script>
    </th:block>
</body>
</html> 